<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
        .box{
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background-color: red;
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>
<body>

<div class="box" style="top:0; left:0">

</div>

</body>

<script>
    let box = document.querySelector('.box');
    let oldStyle=getComputedStyle(box)
    let boxLeft=localStorage.getItem('boxLeft')||0
    let boxTop=localStorage.getItem('boxTop')||0
    box.style.left=boxLeft
    box.style.top=boxTop


    //鼠标按下注册事件
    //事件注册在window上，可以在快速移动时保证就算脱离拖动元素，元素也可以在下一次回到该去的位置
    window.addEventListener('mousedown', (e) => {
        if(e.button !== 0) return
        window.addEventListener('mousemove',divMove)
    })
    window.addEventListener('mouseup', (e) => {
        if(e.button !== 0) return
        localStorage.setItem('boxLeft',box.style.left)
        localStorage.setItem('boxTop',box.style.top)
        window.removeEventListener('mousemove',divMove)
    })

    window.addEventListener('mouseleave',function(){
        window.removeEventListener('mousemove',divMove)
    })
    //元素移动处理函数
    function divMove(e) {
        box.style.left = e.movementX + parseInt(oldStyle.left) + 'px';
        box.style.top = e.movementY + parseInt(oldStyle.top) + 'px';
    }

</script>
</html>
